<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="特征名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入特征名称" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave" v-hasPermi="['trade:feature:save']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['trade:feature:update']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleRemove" v-hasPermi="['trade:feature:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="featureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" />
      <el-table-column label="编号" prop="id" align="center"/>
      <el-table-column label="特征名称" prop="name" :show-overflow-tooltip="true" align="center"/>
      <el-table-column label="特征类型" prop="type" :show-overflow-tooltip="true" align="center"/>
      <el-table-column label="特征参数" prop="params" align="center"/>
      <el-table-column label="创建时间" prop="createdTime" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updatedTime" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['trade:feature:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)" v-hasPermi="['trade:feature:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改特征对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="特征名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入特征名称"/>
        </el-form-item>
        <el-form-item label="特征类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择特征" @change="selectChange" :style="{width: '100%'}">
            <el-option v-for="featureTemplate in featureTemplateOptions" :key="featureTemplate.name" :label="featureTemplate.name" :value="featureTemplate"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="特征参数" prop="params">
          <el-input v-model="form.params" type="textarea" placeholder="请输入特征参数"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveFeature, removeFeature, updateFeature, getFeature, searchFeature } from "@/api/trade/feature";

export default {
  name: "Feature",
  data() {
    const checkJson = (rule , value, callback) => {
      try {
        JSON.parse(value);
      } catch (e) {
          console.log("JSON格式错误")
          callback(new Error('JSON格式错误'));
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 特征表格数据
      featureList: [],
      // 特征模板选项
      featureTemplateOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: undefined
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        name: [
          { required: true, message: "特征名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "特征类型不能为空", trigger: "blur" }
        ],
        params: [
          { required: true, message: "特征参数不能为空", trigger: "blur" },
          { required: true, validator:checkJson, message: "请输入正确的JSON格式", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询特征列表 */
    getList() {
      this.loading = true;
      searchFeature(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.featureList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        type: undefined,
        params: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 选中特征
    selectChange(featureTemplate) {
      // this.form.name = featureTemplate.name;
      this.form.type = featureTemplate.type;
      this.form.params = featureTemplate.params;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleSave() {
      this.reset();
      getFeature().then(response => {
        this.featureTemplateOptions = response.featureTemplates;
        this.open = true;
        this.title = "添加特征";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const featureId = row.id || this.ids
      getFeature(featureId).then(response => {
        this.form = response.data;
        this.featureTemplateOptions = response.featureTemplates;
        this.open = true;
        this.title = "修改特征";
      });
    },
    /** 删除按钮操作 */
    handleRemove(row) {
      const featureIds = row.id || this.ids;
      this.$confirm('是否确认删除特征编号为"' + featureIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return removeFeature(featureIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFeature(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            saveFeature(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }
  }
};
</script>